// pages/myArchive/myArchive.ts
import api from "../../api/index";
import common from "../../common/index";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    navBarHeight: app.globalData.navBarHeight,
    userInfo: app.globalData.user,
    single: false,
    archiveForm: {
      "area": "",
      "age_group": "",
      "gender": "",
      "degree": "",
      "title": "",
      primary_discipline: [],
      secondary_discipline: [],
      "research_plan": [],
      researchTopic: '',
    },
    areaIndex: 0,
    provinces: [
      "北京市", "天津市", "河北省", "山西省", "内蒙古自治区",
      "辽宁省", "吉林省", "黑龙江省", "上海市", "江苏省",
      "浙江省", "安徽省", "福建省", "江西省", "山东省",
      "河南省", "湖北省", "湖南省", "广东省", "广西壮族自治区",
      "海南省", "重庆市", "四川省", "贵州省", "云南省",
      "西藏自治区", "陕西省", "甘肃省", "青海省", "宁夏回族自治区",
      "新疆维吾尔自治区", "香港", "澳门", "台湾"
    ],
    ageIndex: 0,
    ageList: [
      "24岁以下",
      "25-30岁",
      "31-40岁",
      "41-50岁",
      "50岁以上",
    ],
    genderIndex: 0,
    genderList: ['男','女'],
    degreeIndex: 2,
    degreeList:['专科','本科','硕士','博士','其它'],
    titleIndex: 0,
    titleList: ['在校学生','高校教师','中学教师','科研院所研究员','科技公司研究员','科技从业者','其它'],
    primaryDiscipline: '',
    subjectList: [],
    secondaryDiscipline: '',
    secondarySubjectList: [],
    researchPlan: '',
    researchPlanOptions: ['学位论文','课题论文','期刊论文'],
    researchTopic: '',

  },
  observers: {
    // 当一级学科发生变化时，自动加载对应的二级学科
    'primaryDiscipline': function(primaryDiscipline) {
      if (primaryDiscipline && primaryDiscipline.trim() !== '') {
        console.log('检测到一级学科变化，加载二级学科:', primaryDiscipline);
        this.getSubjectKeywords();
      }
    }
  },
  bindAreaPickerChange(e: BaseEvent) {
    this.setData({
      areaIndex: e.detail.value
    })
  },
  bindAgePickerChange(e: BaseEvent) {
    this.setData({
      ageIndex: e.detail.value
    })
  },
  bindGenderChange(e: BaseEvent) {
    this.setData({
      genderIndex: e.detail.value
    })
  },
  bindDegreeChange(e: BaseEvent) {
    this.setData({
      degreeIndex: e.detail.value
    })
  },
  bindTitleChange(e: BaseEvent) {
    this.setData({
      titleIndex: e.detail.value
    })
  },
  bindPrimaryDisciplineChange(e: BaseEvent) {
    console.log(e.detail.value)
    this.setData({
      primaryDiscipline: e.detail.value,
      secondaryDiscipline: '',
    })
    this.getSubjectKeywords()
  },
  bindSecondaryDisciplineChange(e: BaseEvent) {
    this.setData({
      secondaryDiscipline: e.detail.value
    })
  },
  bindResearchPlanChange(e: BaseEvent) {
    this.setData({
      researchPlan: e.detail.value
    })
  },
  async getAllSubject() {
    try {
      const res = await api.getAllSubject()
      if (res.data) {
        this.setData({
          subjectList: res.data
        })
      }
    } catch(e){}
  },
  getSubjectKeywords() {
    const uid = common.getLocalUid()
    api.getSubjectKeywords({
      uid: this.data.userInfo.uid || uid,
      primary_discipline: this.data.primaryDiscipline.split(','),
    }).then((res) => {
      if (res.data) {
        this.setData({
          secondarySubjectList: res.data
        })
      }
    })
  },
  async getUserPortrait(uid: string) {
    let result = null
    try {
      const res = await api.getPortrait({uid})
      if (res.data) {
        if (res.data.primary_discipline) {
          if (typeof res.data.primary_discipline === 'string') {
            res.data.primary_discipline = [res.data.primary_discipline]
          }
        } else {
          res.data.primary_discipline = []
        }
        if (res.data.secondary_discipline) {
          if (typeof res.data.secondary_discipline === 'string') {
            res.data.secondary_discipline = [res.data.secondary_discipline]
          }
        } else {
          res.data.secondary_discipline = []
        }
        result = res.data
        this.setData({
          areaIndex: this.data.provinces.findIndex((item) => item.indexOf(res.data.area) > -1 ),
          ageIndex: this.data.ageList.findIndex((item) => item === res.data.age_group),
          genderIndex: this.data.genderList.findIndex((item) => item === res.data.gender),
          degreeIndex: this.data.degreeList.findIndex((item) => item === res.data.degree),
          titleIndex: this.data.titleList.findIndex((item) => item === res.data.title),
          primaryDiscipline: res.data.primary_discipline.join(','),
          secondaryDiscipline: res.data.secondary_discipline.join(','),
          researchPlan: res.data.research_plan.join(','),
          researchTopic: res.data.research_topic.join(','),
        })
      }
    } catch (e) {
      console.log(e)
    }
    return result
  },
  async getUserInfo(uid: string) {
    const userInfo: any = {}
    try {
      const res: any = await api.getUserInfo({uid})
      if (res && res.uid) {
        userInfo.nickname = res.nickname
        userInfo.icon = res.icon.replace(/.*?(?=\/user_portrait)/, '')
        userInfo.uid = res.uid
        userInfo.is_bind_wechat = res.is_bind_wechat || false
        userInfo.is_bind_external_wechat = res.is_bind_external_wechat || false
      }
    } catch(e) {
      console.log(e)
    }
    return userInfo
  },
  async handleSavePortrait() {
    if (!this.data.researchPlan || !this.data.primaryDiscipline) {
      wx.showToast({
        title: '请填写完整信息'
      })
      return
    }
    const uid = this.data.userInfo.uid || common.getLocalUid()
    try {
      const res = await api.createPortrait({
        uid,  // 用户id，数艾缘知自己的账号体系。
        area: this.data.provinces[this.data.areaIndex],    // 地域
        age_group: this.data.ageList[this.data.ageIndex],   // 年龄段
        gender: this.data.genderList[this.data.genderIndex],  // 性别
        degree: this.data.degreeList[this.data.degreeIndex],  // 学历
        title: this.data.titleList[this.data.titleIndex],  // 职位
        research_plan: this.data.researchPlan.split(','),  // 科研计划
        primary_discipline: this.data.primaryDiscipline.split(','),  // 一级学科
        secondary_discipline: this.data.secondaryDiscipline.split(','), // 二级学科
        research_topic: this.data.researchTopic ? this.data.researchTopic.split(',') : [] // 研究主题
      })
      wx.hideLoading()
      if (res.status === 'success') {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        const userInfo = await this.getUserInfo(uid)
        common.setAppUserInfo(userInfo)
        if (this.data.single) {
          wx.switchTab({
            url: '/pages/index/index'
          })
        } else {
          wx.navigateBack()
        }
      } else {
        wx.showToast({
          title: '保存失败',
          icon: 'error'
        })
      }
    } catch(e){
      wx.hideLoading()
      wx.showToast({
        title: '保存异常',
        icon: 'error'
      })
      console.log(e)
    }
  },
  handleBack() {
    wx.navigateBack()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(query) {
    this.setData({
      single: query.single === 'true'
    })
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    wx.showLoading({
      title: '加载中'
    })
    const uid = common.getLocalUid()
    await this.getAllSubject()
    await this.getUserPortrait(this.data.userInfo.uid || uid)
    wx.hideLoading()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})